package com.sc.ifs.order;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import WeiXinPayV3.WeiXin;
import WeiXinPayV3.XMLUtil;

import com.alibaba.fastjson.JSON;
import com.sc.dal.common.pagination.Page;
import com.sc.dal.common.pagination.PaginationBean;
import com.sc.dal.dto.order.OrderDetailDto;
import com.sc.dal.dto.promotion.PromotionDetailDto;
import com.sc.dal.dto.promotion.PromotionGoodsSkuDto;
import com.sc.dal.mapper.order.OrderMapper;
import com.sc.dal.model.cart.Cart;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.goods.GoodsStock;
import com.sc.dal.model.member.MemberAddress;
import com.sc.dal.model.member.MemberCard;
import com.sc.dal.model.member.MemberNews;
import com.sc.dal.model.order.Express;
import com.sc.dal.model.order.Order;
import com.sc.dal.model.order.OrderBalance;
import com.sc.dal.model.order.OrderDetail;
import com.sc.dal.model.order.OrderPayment;
import com.sc.dal.model.order.OrderShip;
import com.sc.dal.model.order.Orders;
import com.sc.dal.model.order.OrdersPay;
import com.sc.dal.model.order.Products;
import com.sc.dal.model.order.Shop;
import com.sc.dal.model.order.Tax;
import com.sc.dal.model.promotion.PromotionOrderRecord;
import com.sc.service.cart.CartService;
import com.sc.service.consultComment.ConsultCommentService;
import com.sc.service.goods.GoodsService;
import com.sc.service.goods.GoodsSkuService;
import com.sc.service.member.MemberAddressService;
import com.sc.service.member.MemberCardService;
import com.sc.service.member.MemberService;
import com.sc.service.order.OrderService;
import com.sc.service.promotion.PromotionService;
import com.sc.util.ChanPay.pay.AppPay;
import com.sc.util.ChanPay.util.AppPayResult;
import com.sc.util.ChanPay.util.BankCodeNameEnum;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Arith;
import com.sc.util.data.CollectionUtil;
import com.sc.util.data.Common;
import com.sc.util.data.Constants;
import com.sc.util.data.DataUtil;
import com.sc.util.data.DateUtil;
import com.sc.util.data.MakeOrderNum;
import com.sc.util.data.WinXinReturnEnum;
import com.sc.util.exception.ExceptionEnum;

/**
 * @ClassName: AppOrderController
 * @Description: 订单管理
 * @author LeiJia
 * @date 2017年3月13日上午10：14:44
 * @version V1.0
 */
@Controller
@RequestMapping("/app/order")
public class AppOrderController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());	
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private MemberAddressService   memberAddressService;
	
	@Autowired
	private MemberCardService memberCardService;
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private GoodsSkuService goodsSkuService;

	@Autowired
	private CartService cartService;
	
	@Autowired
	private PromotionService promotionService;
	@Autowired
	private ConsultCommentService  consultCommentService;
	
	
	//private static final int CHAN_QPAY_ORDER_EXPIRED_TIME =7;//支付过期时间 //默认7天取值范围：1m～15d。m-分钟，h-小时，d-天。 该参数数值不接受小数点，如1.5h，可转换为90m。
	
	/**
	 * @Title: expressList
	 * @Description 查询快递列表
	 * @date 2017年3月25日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="expressList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> expressList(){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		try{
			List<Express> list = orderService.selectByParam();
		   	resultMap.put("data", list);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);		   	
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}		
		return resultMap;
	}
	/**
	 * @Title: orderList
	 * @Description 查询订单列表
	 * @param queryStatus 查询状态 0：全部,1：待付款,2:待发货，3:待收货，4：待评价 ，5：退换货
	 * @date 2017年3月16日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="orderQueryStatusCountList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> orderQueryStatusCountList(String memberId ){		
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();		
		try {
			Orders order = new Orders();
			// 添加查询条件
			order.setMemberId(memberId);
			//订单查询状态 0：全部,1：待付款,2:待发货，3:待收货，4：待评价 ，5：退换货 
			order.setQueryStatus("0");
			int queryStatus0count =orderService.counts(order);

			order.setQueryStatus("1");
			int queryStatus1count =orderService.counts(order);			

			order.setQueryStatus("2");
			int queryStatus2count =orderService.counts(order);			

			order.setQueryStatus("3");
			int queryStatus3count =orderService.counts(order);
			

			order.setQueryStatus("4");
			int queryStatus4count =orderService.counts(order);

			order.setQueryStatus("5");
			int queryStatus5count =orderService.counts(order);
			
			
			resultMap.put("queryStatus0count", queryStatus0count);
			resultMap.put("queryStatus1count", queryStatus1count);
			resultMap.put("queryStatus2count", queryStatus2count);
			resultMap.put("queryStatus3count", queryStatus3count);
			resultMap.put("queryStatus4count", queryStatus4count);
			resultMap.put("queryStatus5count", queryStatus5count);
			
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("分页查订单商品异常！");
		}
		return resultMap;
	}
	
	/**
	 * @Title: orderList
	 * @Description 查询订单列表
	 * @param queryStatus 查询状态 0：全部,1：待付款,2:待发货，3:待收货，4：待评价 ，5：退换货
	 * @date 2017年3月16日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="orderList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> orderList(Integer currPage,Integer pageSize,String memberId,String queryStatus ){		
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		Page page = new Page();
		// 传入页号
		page.setCurrPage(currPage);
		// 传入每页记录数
		page.setPageSize(pageSize);
		
		Orders order = new Orders();
		// 添加查询条件
		order.setMemberId(memberId);
		order.setQueryStatus(queryStatus);
		List<Orders> resultList = new ArrayList<Orders>();
		int totalRecords = 0;
		int totalPage = 0;
		try {
			if(currPage == null || pageSize == null || Common.isEmpty(memberId) || Common.isEmpty(queryStatus)){				
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
		    }
			PaginationBean<Orders> result = orderService.getPagingDatas(order,
					page, "count", "selectByParam",OrderMapper.class);
			resultList = result.getPageList();
			for(Orders o:resultList){
				List<Products> porducts = o.getProducts();
				if(porducts!= null && porducts.size() >0){
					for(Products pro:porducts){
						String orderId = pro.getOrderId();
						Integer goodsId = pro.getProductId();
						List<String> countList = consultCommentService.findIsComment(orderId,goodsId);
						if(countList!=null && countList.size()>0 ){
							pro.setIsCommentCount(countList.get(0));
						}else{
							pro.setIsCommentCount("0");
						}
						//根据会员的代理商等级查询代理等级的商品折扣率
						//pro = goodsService.discoutProducts(pro, memberId);
						if(Common.isNotEmpty(pro.getPicture()))
						   pro.setPicture(ConfigBeanAdapter.fileAccessAddress+pro.getPicture());
					}
				}
			}
			totalRecords = result.getTotalRecords();
			totalPage = result.getTotalPage();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("分页查订单商品异常！");
		
		}
		resultMap.put("count", totalRecords);
		resultMap.put("pages", totalPage);
		resultMap.put("data", resultList);
		return resultMap;
	}
	/**
	 * @Title: oneOrder
	 * @Description 根据订单ID查询订单中订单详情
	 * @date 2017年3月16日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value = "oneOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> oneOrder(String orderId){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			if(Common.isEmpty(orderId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
            OrderDetailDto dto = orderService.selectOrderDetailByOrderId(orderId);
			List<Products> list = dto.getProducts();
			if(list != null && list.size() >0){
				for(Products product:list){
					//根据会员的代理商等级查询代理等级的商品折扣率
					/*Map<String,Object> agentInfoMap = memberService.selectAgentInfoByMemberId(dto.getMemberId());
					if(agentInfoMap != null && agentInfoMap.size() > 0 ){
						if(agentInfoMap.get("discount") != null){
							double discount = (double)agentInfoMap.get("discount");
							product.setDiscountMarketPrice(product.getMarketPrice().multiply(new BigDecimal(discount)).setScale(2, BigDecimal.ROUND_HALF_UP));	
							product.setDiscountRate(discount);
						}
					}*/
					String imgUrl = product.getImgUrl();
					String imgUrl_new = "";
					if(Common.isNotEmpty(imgUrl)){
						String[] urls = imgUrl.split(",");
						for(String url:urls){
							imgUrl_new += ConfigBeanAdapter.fileAccessAddress + url +",";
						}
						product.setImgUrl(imgUrl_new);
					}
					product.setPicture(ConfigBeanAdapter.fileAccessAddress + product.getPicture());
				}
			}
			resultMap.put("data", dto);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
	
	
	/**
	 * @Title: tallyOrders
	 * @Description 结算订单(校验数据并获取促销列表)
	 * @param param
	 * @date 2017年4月183日下午14:04
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="tallyOrders")
	@ResponseBody
	public Map<String,Object> tallyOrders(String param){
		OrderBalance balance = null;
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		try{
			balance = JSON.parseObject(param, OrderBalance.class);   
			if(param == null || balance == null){				
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
			}
			List<Shop> shops = balance.getShops();
			if(shops == null){				
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
			}
			//订单创建人
			String memeberId = balance.getMemberId();
			if(Common.isEmpty(memeberId)){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
			}
			String stockMessage ="";//提示信息
			for(Shop shop : shops){
				shop = orderService.getShop(shop,memeberId); //计算该店铺订单的商品总数量与订单总额
				//商品
				List<Products> products = shop.getProducts();
				if(products == null){				
	    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
	    			return resultMap;
				}

				//商品促销活动				
				for(Products product :products){
					List<Map<String,Object>> goodsProMapList = new ArrayList<Map<String, Object>>();
					if(product.getProductId() == null){						
		    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PRODUCT_ID_IS_NOT_NULL);
		    			return resultMap;
					}
					Goods good= goodsService.selectOne(product.getProductId());
					if(Common.isNotEmpty(good.getPicture()))
						product.setPicture(ConfigBeanAdapter.fileAccessAddress+good.getPicture());
					product.setProductName(good.getName());
					product.setMarketPrice(good.getMarketPrice());
					//根据会员的代理商等级查询代理等级的商品折扣率
				    product = goodsService.discoutProducts(product, memeberId);
					if(Common.isNotEmpty(product.getGoods_sku_id())){
						String[] goods_sku_ids = product.getGoods_sku_id().split(",");
						String goods_sku_values="";
						if(goods_sku_ids.length > 0){
							for(String sku_id: goods_sku_ids){
								Map<String,Object> paramMap = new LinkedHashMap<String, Object>();	
								paramMap.put("goods_sku_id", sku_id);
								paramMap = goodsSkuService.selectGoodsSkuById(paramMap);
								if(paramMap != null && paramMap.size() > 0){
									goods_sku_values += paramMap.get("base_sku_name").toString() +":"+ paramMap.get("base_sku_value_name").toString() +",";
									
								}
							}
						}
				        String[] skuInfoArrs = goods_sku_values.split(",");

						GoodsStock goodsStock = new GoodsStock();
						goodsStock.setGoodsId(product.getProductId());
						int stocknum = goodsService.getProductStock(goodsStock,skuInfoArrs);
						product.setProductStock(stocknum);
						if(stocknum == 0){
							products.remove(product);  //如果商品库存为0 商品失效不再返回该商品
							stockMessage += good.getName() + ",商品对应规格库存不足,"+"该商品已经失效"+"\n";
							continue;
						}else if(stocknum < 0 || stocknum < product.getQuantity()){
							product.setProductDetail(good.getName() + "商品库存不足"+"请修改购物车商品数量");
							stockMessage += good.getName() + ",商品库存不足,"+"请修改购物车商品数量"+"\n";
						}else{
							product.setProductDetail(good.getName() + "商品库存充足");
						}
				
				}

					//判断部分商品活动集合中是否已有该商品参与促销了
					if(isGoodsIdNotExistInGoodsProMapList(goodsProMapList,product.getProductId())){
						//查询商品参与的促销活动
						List<PromotionGoodsSkuDto>  goodsProList = promotionService.getGoodsProInfo(product.getProductId());
						if(goodsProList != null && goodsProList.size() > 0){
							for(PromotionGoodsSkuDto goodsSkuDto : goodsProList){						
								List<PromotionDetailDto> goodsProDetailList = promotionService.selectProDetailByProId(goodsSkuDto.getPro_id());
								for(PromotionDetailDto proDetailDto :goodsProDetailList){
		                            Date now_time = new Date(); //现在时间
								    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
								    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
								    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
										Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
										//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
										proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
										proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
										proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
										String pro_type = proDetailDto.getPro_type();
										String pro_money = proDetailDto.getPro_money();
										String pro_count = proDetailDto.getPro_count();
										String pro_rate = proDetailDto.getPro_rate();								

										String pro_gooods = proDetailDto.getPro_goods();
										proDetailMap.put("proType", pro_type);//促销类型
										proDetailMap.put("productId", product.getProductId());
										proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
										proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
										if(proDetailMap.get("discountRate") != null){
											BigDecimal $price = product.getDiscountMarketPrice();
											if($price == null){
												$price = product.getMarketPrice();
											}
											BigDecimal $total = Arith.mul($price, new BigDecimal(product.getQuantity())).setScale(2, BigDecimal.ROUND_HALF_UP);
											String $rate = (String) proDetailMap.get("discountRate");
											BigDecimal $discountAoumnt = Arith.mul(new BigDecimal($rate), $total).setScale(2, BigDecimal.ROUND_HALF_UP);
											$discountAoumnt = Arith.sub($total, $discountAoumnt);
											proDetailMap.put("discountAmount",$discountAoumnt);
											
										}
										if(goodsWhetherMeetWholeActivity(pro_type,proDetailMap,product)){
											goodsProMapList.add(proDetailMap);
										}
								    }
								}
							}
						}
						product.setGoodsProMapList(goodsProMapList);
					}
			    
			}
		    //计算订单的促销方案
			List<Map<String,Object>> wholeOrderPro = new ArrayList<Map<String, Object>>();
			//查询所有促销活动
			List<Map<String,Object>> proDetailDtoMapList  =  promotionService.selectByParam(null);
			if(proDetailDtoMapList != null && proDetailDtoMapList.size() >0){
				for(Map<String,Object> map :proDetailDtoMapList){
                    Date now_time = new Date(); //现在时间
				    Date pro_start = DateUtil.dateStrToYMDHMSDate(map.get("pro_start").toString()); //促销开始时间
				    Date pro_end  = DateUtil.dateStrToYMDHMSDate(map.get("pro_end").toString()); //促销结束时间

				    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
						Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
						String pro_type ="";
						if(map.get("pro_type") != null)
					       pro_type = map.get("pro_type").toString();
						proDetailMap.put("proType", pro_type);
						String pro_money ="";
						if(map.get("pro_money") != null)
						   pro_money = map.get("pro_money").toString();
						String pro_count = "";
						if(map.get("pro_count") != null)
						   pro_count = map.get("pro_count").toString();
						String pro_rate = "";
						if(map.get("pro_rate") != null)
						   pro_rate =map.get("pro_rate").toString();
						//String pro_title="";
						//if(map.get("pro_title") != null)
						//	pro_title =  map.get("pro_title").toString();
						//proDetailMap.put("proTitle", pro_title);//促销名称
						String pro_detail_id="";
						if(map.get("pro_detail_id") != null)
							pro_detail_id =  map.get("pro_detail_id").toString();
						proDetailMap.put("proDetailId", Integer.valueOf(pro_detail_id));
						String ext="";
						if(map.get("ext") != null){
							ext = map.get("ext").toString();
						}
						proDetailMap.put("proDetailTitle",ext);//促销活动名称
						String ext1="";
						if(map.get("ext1") != null){
							ext1 = map.get("ext1").toString();
						}
						proDetailMap.put("proDetailNote",ext1);//促销活动备注
						String pro_gooods = "";
						if(map.get("pro_goods") != null )
							pro_gooods = map.get("pro_goods").toString();
						proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
						if(proDetailMap.get("discountRate") != null){
							String $rate = (String) proDetailMap.get("discountRate");
							BigDecimal $discountAoumnt = Arith.mul(new BigDecimal($rate), shop.getTotalAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
							$discountAoumnt = Arith.sub( shop.getTotalAmount(), $discountAoumnt);
							proDetailMap.put("discountAmount",$discountAoumnt);
							
						}
						if(orderWhetherMeetWholeActivity(pro_type,proDetailMap,shop)){
							wholeOrderPro.add(proDetailMap);
						}
				    }
				}
			}
		    shop.setPromotions(wholeOrderPro);

		 }
			resultMap.put("maId",balance.getMaId());
			resultMap.put("memberId",balance.getMemberId());
			resultMap.put("shops", shops);
			if(Common.isNotEmpty(stockMessage)){
				resultMap.put("stockMessage", stockMessage);
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_TALLY_SUCCESS);
			}
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
		}
		return resultMap;
	}
	//判断部分商品活动集合中是否已有该商品参与促销了
	public boolean isGoodsIdNotExistInGoodsProMapList (List <Map<String,Object>> goodsProMapList ,Integer productId){
		if(goodsProMapList == null || goodsProMapList.size() ==0){
			return true;
		}
		for(Map<String,Object> map :goodsProMapList){
			if(map.get("productId").toString().equals(productId+"")){
				return false;
			}
		}
		return true;
	}
	//判断商品列表是否存在同一商品不同规格的商品
	public boolean isExistTheSameSpecificationGoods(Products product ,List<Products> products){
		for(Products p: products){
			if(product.getProductId() == p.getProductId()){
				if(!product.getGoods_sku_id().equals(p.getGoods_sku_id())){
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * @title 判断订单中的商品是否满足部分活动 
	 * @param pro_type
	 * @param proDetailMap
	 * @param product
	 * @return
	 */
	public boolean goodsWhetherMeetWholeActivity(String pro_type, Map<String, Object> proDetailMap, Products product){
		boolean flag = false;
		int  itemnum =product.getQuantity(); //商品数量
        BigDecimal marketPrice = product.getMarketPrice(); //商品市场价
        BigDecimal totalAmount =  marketPrice.multiply(new BigDecimal(itemnum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        switch(pro_type){
			case "0": //订单满减
				if(proDetailMap.get("mustQuantity") != null){
					System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if(itemnum >=Integer.valueOf(proDetailMap.get("mustQuantity").toString())){
						flag = true;
					}
				}
				break;
			case "1": //商品满减
				if(proDetailMap.get("mustQuantity") != null){
					System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( totalAmount.compareTo(new BigDecimal(proDetailMap.get("mustQuantity").toString())) >=0 ){
						flag = true;
					}
				}
				break;
			case "2": //商品满赠
				if(proDetailMap.get("mustQuantity") != null){
					System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
			case "3":  //商品打折
				if(proDetailMap.get("mustQuantity") != null){
					System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
	        }
		return flag;
	}
	/**
	 * @title 判断订单是否满足整单活动 
	 * @param proDetailMap
	 * @param shop
	 * @return flag true可以参与活动,false不能参与活动
	 */
	public boolean orderWhetherMeetWholeActivity(String pro_type,Map<String ,Object> proDetailMap ,Shop shop){
		boolean flag= false;
		BigDecimal totalAmount = shop.getTotalAmount(); //订单总金额
		int itemnum = shop.getItemnum(); //订单商品数量		
		switch(pro_type){
			case "0": //订单满减
				if(proDetailMap.get("mustQuantity") != null){
					System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if(itemnum >=Integer.valueOf(proDetailMap.get("mustQuantity").toString())){
						flag = true;
					}
				}
				break;
			case "1": //商品满减
				if(proDetailMap.get("mustQuantity") != null){
					System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( totalAmount.compareTo(new BigDecimal(proDetailMap.get("mustQuantity").toString())) >=0 ){
						flag = true;
					}
				}
				break;
			case "2": //商品满赠
				if(proDetailMap.get("mustQuantity") != null){
					System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
			case "3":  //商品打折
				if(proDetailMap.get("mustQuantity") != null){
					System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
	}
		
		return flag;
	}
	/**
	 * 封装促销活动返回集合
	 * @param proDetailMap
	 * @param pro_type
	 * @param pro_money
	 * @param pro_count
	 * @param pro_rate
	 * @param pro_gooods
	 * @return
	 */
	public Map<String ,Object> proDetailMap(Map<String ,Object> proDetailMap,String pro_type,String pro_money,String pro_count,String pro_rate,String pro_gooods){
		 List<Goods> goodsList =new ArrayList<Goods>();//满赠商品列表  
			String[] goods_ids =null;
			if(Common.isNotEmpty(pro_gooods)){
				goods_ids =pro_gooods.split(",");
				for(String goods_id : goods_ids){
					Goods goods = goodsService.selectByPrimaryKey(Integer.valueOf(goods_id));
					goodsList.add(goods);
				}
			}
		switch(pro_type){
			case "0": //订单满减
				if(Common.isNotEmpty(pro_money)){
					proDetailMap.put("mustQuantity", pro_money.split(":")[0]);
					proDetailMap.put("discountAmount", pro_money.split(":")[1]);
				}
				break;
			case "1": //商品满减
				if(Common.isNotEmpty(pro_money)){
					proDetailMap.put("mustQuantity", pro_money.split(":")[0]);
					proDetailMap.put("discountAmount", pro_money.split(":")[1]);
				}
				break;
			case "2": //商品满赠
				if(Common.isNotEmpty(pro_count)){
					proDetailMap.put("mustQuantity", pro_count.split(":")[0]);
					proDetailMap.put("giveNumber", pro_count.split(":")[1]);
					proDetailMap.put("giveList", goodsList);
				}
				break;
			case "3":  //商品打折
				if(Common.isNotEmpty(pro_count)){
					proDetailMap.put("mustQuantity", pro_count);//商品满足数量
					BigDecimal rate = new BigDecimal(new Double(pro_rate)/100).setScale(2, BigDecimal.ROUND_HALF_UP);
					proDetailMap.put("discountRate",rate.toString());//商品打折率
				}
				break;
		}
		return proDetailMap;
	}
	
	/**
	 * @Title: generateOrders
	 * @Description 提交订单(仿淘宝天猫) 运费系统后台重算一遍，订单总金额要在订单参与促销活动的总金额基础上再累加
	 * @param param
	 * @date 2017年3月13日上午08:49:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="generateOrders")
	@ResponseBody
	@Transactional
	public Map<String,Object> generateOrders(String param){
		OrderBalance balance = null;
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
	    int addOrderResult=0;
	    String exception_desc ="";
		List<Order> orders = new ArrayList<Order>();
	    try{
	    	balance = JSON.parseObject(param, OrderBalance.class);   
			if(param == null || balance == null){				
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			//ex苏宁易购订单，包含四部分：1.配送信息；2.支付方式；3.商品及服务信息；4.发票信息；5.结算信息
			//创建订单
			//订单编号
			List<Shop> shops = balance.getShops();
			if(shops == null){				
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			//订单创建日期
			Date createDate = new Date();
			//订单创建人
			String memeberId = balance.getMemberId();
			if(Common.isEmpty(memeberId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}	
			for(Shop shop : shops){
				shop = orderService.getShop(shop,memeberId); //计算该店铺订单的商品总数量与订单总额
				MakeOrderNum  orderNum=new MakeOrderNum();
				String orderId =orderNum.makeOrderNum();
				//商品
				List<Products> products = shop.getProducts();
				if(products == null){				
	    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
	    			return resultMap;
				}
				//String orderId = Common.getUUID();
				Order order  = new Order();
				order.setOrderId(orderId);
				order.setMemberId(memeberId);
				order.setSource(Constants.OrderDetail.OrderSource.ORDER_SOURCEB); // 1：pc平台；2：手机触屏；3：微信商城
				String expressId = shop.getExpressId();
				if(Common.isEmpty(expressId)){
	    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_EXPRESS_ID_IS_NOT_NULL);
	    			return resultMap;
				}
				Express express = orderService.selectByExpressById(Integer.valueOf(expressId));
				if(express != null){ 
					//order.setExt1(expressId);
					order.setShipMethod(express.getName()+"¥"+express.getFee());
					order.setShipMoney(express.getFee());
					//order.setExpressCode(express.getCode());
					order.setExpressName(express.getName());
				}
				
				//发货地址
				MemberAddress address = this.selectAddressById(balance.getMaId());
				if(address == null){
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_MEMBER_ADDRESS_NOT_NULL);
	    			return resultMap;
				}
				//生成订单配送信息
				OrderShip orderShip = new OrderShip(orderId,//订单id
						address.getName(),//收件人名称
						address.getProvince()+address.getCity()+address.getCounty()+address.getStreet(),//收件详细地址
						address.getProvinceCode(),//省级行政区域代码
						address.getProvince(), //省级行政区域名称
						address.getCityCode(),//市级行政区域代码
						address.getCity() ,//市级行政区域名称
						address.getCityCode(),//县级行政区域代码
						address.getCounty() ,//县级行政区域名称
						address.getTel(),//收件人联系电话
						address.getPostcode(),//邮政编码 
						"1"//收件人性别
						);

				exception_desc =  ExceptionEnum.DATA_INSERT.getDesc();
				orderService.insert(orderShip);
				
				//发票
				Tax tax = shop.getTax();
				if(tax == null){
					order.setIsTax(Constants.OrderDetail.TaxType.TAX_TYPEA);
				}else{
					order.setScoreU(tax.getScoreU());
					order.setIsTax(tax.getIsTax());
					order.setTaxType(tax.getTaxType());
					order.setCostTax(tax.getCostTax());
					order.setTaxCompany(tax.getTaxCompany());
					order.setTaxContent(tax.getTaxContent());
					order.setInvoiceAmount(tax.getInvoiceAmount());
				}
				
	            //订单信息
				if(Common.isEmpty(shop.getSellerId())){
					order.setSellerId(Constants.SELLERID);		
				}else{	
					order.setSellerId(shop.getSellerId());		
				}
				order.setMemo(shop.getMemo());//订单备注
				order.setWeight(shop.getWeight());				
				order.setCreateDate(createDate);
				order.setCreater(memeberId);
				order.setPayStatus(Constants.OrderDetail.OrderPay.PAY_STATUSC);
				order.setStatus(Constants.OrderDetail.OrderStatus.ORDER_STATUSA);
				order.setIsComment(Constants.OrderDetail.OrderStatus.IS_COMMENTA);//是否评论0：没有评论，1：有评论
				order.setIsValid(Constants.OrderDetail.OrderStatus.IS_VALIDA);//订单是否失效
				order.setIsDelete(Constants.OrderDetail.OrderStatus.IS_DELETEA);//订单是否删除
				order.setPromotionType(Constants.OrderDetail.OrderSales.PROMOTION_TYPEA); //销售类型 1:普通订单;2:预售订单; 
				order.setShipStatus(Constants.OrderDetail.OrderDeliver.SHIP_STATUSA);//发货状态
				order.setModifier(memeberId);
				order.setModifyDate(createDate);
				order.setPayDeadline(DateUtil.getDateAfter(createDate,  Integer.valueOf(ConfigBeanAdapter.chan_qpay_order_expired_time)));//支付截止时间默认7天(真正起作用的是选择完支付方式后会再次修改截止付款时间)
				//order.setPmtGoods(0.0); //商品促销优惠金额
				//order.setPmtOrder(0.0);  //订单促销优惠金额
	            order.setIsPmtOrder(Constants.OrderDetail.OrderStatus.IS_PMT_ORDERB);
				//促销活动详情ID
				String proDetailId = shop.getProDetailId();
				PromotionDetailDto proDetailDto = null; //促销活动详情
				if(Common.isNotEmpty(proDetailId)){		
					proDetailDto  = promotionService.selectProDetailByPrimaryKey(Integer.valueOf(proDetailId));	
					if(proDetailDto == null ){						
		    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PROMOTION_DETAIL_IS_NOT_FIND_ERROR);
		    			return resultMap;
					}
	                order.setProType(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_B); //促销方式
					//整单促销
					String pro_type = proDetailDto.getPro_type();
					String pro_money = proDetailDto.getPro_money();
					String pro_count = proDetailDto.getPro_count();
					String gift_pro_goods = proDetailDto.getPro_goods();
					String pro_rate = proDetailDto.getPro_rate();
					switch(pro_type){
						case "0": //订单满减
							if(Common.isNotEmpty(pro_money)){
								order.setPmtOrder(new Double(pro_money.split(":")[1]));
							}
							break;
						case "1": //商品满减
							if(Common.isNotEmpty(pro_count)){
								order.setPmtOrder(new Double(pro_money.split(":")[1]));
							}
							break;
						case "2": //商品满赠
							if(Common.isNotEmpty(pro_count)){
								order.setGiftGoods(gift_pro_goods);
							}
							break;
						case "3":  //商品打折
							if(Common.isNotEmpty(pro_count) && Common.isNotEmpty(pro_rate)){
								BigDecimal rate = new BigDecimal(pro_rate);
								rate = Arith.sub(new BigDecimal(100), rate);
								BigDecimal pmtOrder_ =new BigDecimal(shop.getTotalAmount().multiply(rate).doubleValue()/100).setScale(2,   BigDecimal.ROUND_HALF_UP);
								double $pmtOrder =Arith.add( order.getPmtOrder()==null?0d:order.getPmtGoods(), pmtOrder_.doubleValue()) ;
								order.setPmtOrder($pmtOrder);//计算打折后的订单订单促销优惠金额
							}
							break;
				   }

				   order.setIsPmtOrder(Constants.OrderDetail.OrderStatus.IS_PMT_ORDERA);
				   order.setProDetailId(proDetailId);
				}
	            String pro_goods = ""; //记录参与促销活动的商品ID以英文逗号隔开
	            String pro_DetailIds=""; 
	            for(Products product :products){
					//根据会员的代理商等级查询代理等级的商品折扣率
				    product = goodsService.discoutProducts(product, memeberId);
					//促销活动详情ID
					String pro_DetailId = product.getProDetailId();
					if(Common.isNotEmpty(pro_DetailId)){
	    				pro_DetailIds += pro_DetailId+",";
	    				PromotionDetailDto pro_DetailDto = promotionService.selectProDetailByPrimaryKey(Integer.valueOf(pro_DetailId));//促销活动详情
						if(pro_DetailDto == null ){						
			    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PROMOTION_DETAIL_IS_NOT_FIND_ERROR);
			    			return resultMap;
						}
		                order.setProType(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_A); //促销方式
						pro_goods += "" +product.getProductId();
						String pro_type = pro_DetailDto.getPro_type();
						String pro_money = pro_DetailDto.getPro_money();
						String pro_count = pro_DetailDto.getPro_count();
						String gift_pro_goods = pro_DetailDto.getPro_goods();
						String pro_rate = pro_DetailDto.getPro_rate();
						switch(pro_type){
							case "1": //商品满减
								if(Common.isNotEmpty(pro_money)){
									order.setPmtGoods(new Double(pro_money.split(":")[1]));
								}
								break;
							case "2": //商品满赠
								if(Common.isNotEmpty(pro_count)){
									order.setGiftGoods(gift_pro_goods);
								}
								break;
							case "3":  //商品打折
								if(Common.isNotEmpty(pro_count) && Common.isNotEmpty(pro_rate)){
									BigDecimal rate = new BigDecimal(pro_rate);
									rate = Arith.sub(new BigDecimal(100), rate);																
									BigDecimal pmtGoods_ = new BigDecimal(0);
									if(product.getDiscountMarketPrice() != null){
										pmtGoods_ = new BigDecimal(product.getDiscountMarketPrice().multiply(new BigDecimal(product.getQuantity())).multiply(rate).doubleValue()/100).setScale(2,   BigDecimal.ROUND_HALF_UP);
									}else{
										pmtGoods_ = new BigDecimal(product.getMarketPrice().multiply(new BigDecimal(product.getQuantity())).multiply(rate).doubleValue()/100).setScale(2,   BigDecimal.ROUND_HALF_UP);
									}
									double $pmtGoods_ =Arith.add( order.getPmtGoods()==null?0d:order.getPmtGoods(), pmtGoods_.doubleValue()) ;
									order.setPmtGoods($pmtGoods_);//计算打折后的订单订单促销优惠金额
								}
								break;
					   }
					}
	            }
	            if(Common.isNotEmpty(pro_DetailIds))
		            order.setProDetailId(pro_DetailIds);
				order.setItemnum(shop.getItemnum());
				if(order.getPmtGoods() != null){
					BigDecimal $totalAmount = Arith.sub(shop.getTotalAmount(), new BigDecimal(order.getPmtGoods())); //去除优惠金额之后的订单总额
					if(express != null){
						$totalAmount  =(Arith.add($totalAmount , express.getFee())); //计算含运费之后的订单总金额
					}	
					order.setTotalAmount($totalAmount);
				}else if(order.getPmtOrder() != null ){
					BigDecimal $totalAmount = Arith.sub(shop.getTotalAmount(), new BigDecimal(order.getPmtOrder())); //去除优惠金额之后的订单总额
					if(express != null){
						$totalAmount  =(Arith.add($totalAmount , express.getFee())); //计算含运费之后的订单总金额
					}	
					order.setTotalAmount($totalAmount);
				}else{
					BigDecimal $totalAmount =shop.getTotalAmount();
					if(express != null){
						$totalAmount  =(Arith.add($totalAmount , express.getFee())); //计算含运费之后的订单总金额
					}	
					order.setTotalAmount($totalAmount);
				}
	            order.setProGoods(pro_goods); //记录参与部分商品活动促销的商品ID
            	exception_desc = ExceptionEnum.DATA_ORDER_CREATE_ERROR.getDesc();
	            addOrderResult = orderService.insert(order);
	            if(addOrderResult > 0){
	            	logger.info("订单添加成功");
	            	if(Common.isNotEmpty(pro_DetailIds) || Common.isNotEmpty(proDetailId)){ //添加订单促销活动记录
	                	//记录订单促销活动记录
	                	PromotionOrderRecord record = new PromotionOrderRecord();
	                	record.setCreateTime(createDate);
	                	record.setOrderId(orderId);
	                	if(Common.isNotEmpty(pro_DetailIds)){
	                        record.setProDetailId(pro_DetailIds);                    		
	                	}
	                	if(Common.isNotEmpty(proDetailId)){
	                        record.setProDetailId(proDetailId);
	                	}
	                	promotionService.insertOrderProRecord(record);    
	            	}           	
	            	
	            }
				//生成订单详情
				for(Products product :products){					
					OrderDetail detail = new OrderDetail();
					detail.setOrderId(orderId);
					if(product.getProductId() == null){						
		    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PRODUCT_ID_IS_NOT_NULL);
		    			return resultMap;
					}
					detail.setProductId(product.getProductId());
					detail.setNumber(product.getQuantity());
					Goods good= goodsService.selectOne(product.getProductId());
					product.setMarketPrice(good.getMarketPrice());
					product = goodsService.discoutProducts(product, memeberId);
					if(product.getDiscountMarketPrice() == null){
						detail.setMarketPrice(product.getMarketPrice());
					}else{
						detail.setMarketPrice(product.getDiscountMarketPrice());
					}

					detail.setProductName(good.getName());
					detail.setIsComment(Constants.OrderDetail.OrderStatus.IS_VALIDA);//是否评论0：没有评论，1：有评论
					detail.setScore(product.getScore());  //赠送积分
					if(Common.isNotEmpty(product.getGoods_sku_id())){
						detail.setGoods_sku_id(product.getGoods_sku_id());; //商品规格ID
						String[] goods_sku_ids = product.getGoods_sku_id().split(",");
						String goods_sku_values="";
						if(goods_sku_ids.length > 0){
							for(String sku_id: goods_sku_ids){
								Map<String,Object> paramMap = new LinkedHashMap<String, Object>();	
								paramMap.put("goods_sku_id", sku_id);
								paramMap = goodsSkuService.selectGoodsSkuById(paramMap);
								if(paramMap != null && paramMap.size() > 0){
									goods_sku_values += paramMap.get("base_sku_name").toString() +":"+ paramMap.get("base_sku_value_name").toString() +",";
								}
							}
						}
						detail.setGoods_sku_info(goods_sku_values);; //商品规格信息
					    //减少商品对应的的规格库存数量
					  /*  GoodsStock stock = new GoodsStock();
				        if(Common.isNotEmpty(goods_sku_values)){
						     stock = goodsService.getGoodsStock(stock, goods_sku_values.split(","));
				        }
						stock.setGoodsId(product.getProductId());
				        stock.setSaleBaseQuantity(Integer.valueOf((product.getQuantity())));
						int updateGoodsStockResult = goodsService.updateGoodsStock(stock);
						if(updateGoodsStockResult  <= 0){
			    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_STOCK_UPDATE_ERROR);
			    			return resultMap;
							logger.info("商品id为：" + product.getProductId() + " 规格信息为："+ product.getGoods_sku_id() +  " 库存修改失败！");
						}else{
							logger.info("商品id为：" + product.getProductId() + " 规格信息为："+ product.getGoods_sku_id() +  " 库存修改成功！");
						}*/
					
				}
				exception_desc = ExceptionEnum.DATA_ORDER_CREATE_ERROR.getDesc();
			    orderService.insert(detail);
			    if(addOrderResult >0){
			    	//清除去购物车商品
			    	Cart cart = new Cart();
			    	cart.setProductId(product.getProductId());
			    	cart.setGoods_sku_id(product.getGoods_sku_id());
			    	cart.setMemberId(balance.getMemberId());
			    	List<Cart> cl =cartService.selectByCartInfo(cart);
			    	if(cl != null && cl.size() >0){
			    		Cart c = cl.get(0);
			    		c.setIsDelete(Constants.IS_DELETEB);
			    		int resultDeleteProductResult = cartService.deleteProduct(c);
			    		if(resultDeleteProductResult >0 ){
			    			logger.info("删除购物车商品成功！");
			    		}
			    	}
			    }
			}
				//生成订单支付信息
			    OrderPayment payment = new OrderPayment();
			    payment.setPaymentId(Common.getUUID());
			    payment.setCreateDate(createDate);
			    payment.setCreater(memeberId);
			    payment.setCurMoney(shop.getTotalAmount());  //客户支付货币金额
			   // payment.setCurrency(currency);  //货币种类
			    payment.setIsValid(Constants.IS_VALIDA);    //是否有效（1：有效；0：无效）
			    payment.setMoney(shop.getTotalAmount());//支付金额
			    payment.setMemberId(memeberId);
			   // payment.setMemo(shop.getMemo()); //支付备注
			    payment.setModifier(memeberId);
			    payment.setModifyDate(createDate);
			   // payment.setMoney(shop.getTotalAmount()); //支付金额
			    payment.setOrderId(orderId);
			   // payment.setPayer(payer);  //付款人名称
			   // payment.setPaymentAccount(paymentAccount); //收款帐号
			   // payment.setPaymentBank(paymentBank); //收款银行
			   // payment.setPaymentId(paymentId); //支付ID，主键
			   // payment.setPayTime(payTime);   //支付时间
			   // payment.setPayType(payType); //支付类型 1:在线支付;2:线下支付;3:预存款支付
			   // payment.setPayWay(payWay); //支付方式名称
			    payment.setSellerId(Constants.SELLERID);
			    
			    payment.setStatus(Constants.OrderDetail.OrderPay.PAY_STATUSC); //支付状态1:支付成功,2:支付失败;3:未支付;4:处理异常;5:非法参数;\r\n 6:已付款至担保方;7:超时;8:准备中; 
			    payment.setType(Constants.OrderDetail.OrderPay.PayType.TYPEB); //类型（0：退款，1：付款）
				exception_desc = ExceptionEnum.DATA_ORDER_PAYMENT_CREATE_ERROR.getDesc();
			    orderService.insert(payment);		
				orders.add(order);
					
			}
			
			resultMap.put("data",orders);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_CREATE_SUCCESS);
	    }catch(Exception e){
			e.printStackTrace();
	    	throw new RuntimeException( exception_desc);
	    }
		return resultMap;
	}
	/**
	 * 获取用户的发货地址
	 * @param maId
	 * @return
	 */
	private MemberAddress selectAddressById(String maId) {
		return memberAddressService.selectAddressById(maId);
	}

	/**
	 * @Title: cancelOrDeleteOrder
	 * @Description 取消/删除订单 
	 * @param orderId
	 * @param status 0:取消订单 ;1：删除订单
	 * @date 2017年3月13日上午11:50:15
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="cancelOrDeleteOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> cancelOrDeleteOrder(String orderId,String status){		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			if(Common.isEmpty(orderId) || Common.isEmpty(status)){				
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
			}
			Order order = new Order();
			order.setOrderId(orderId);
			if(Constants.OrderDetail.STATUSA.equals(status)){
				order.setIsValid(Constants.OrderDetail.OrderStatus.IS_VALIDB);
				/*
				final String orderId_ = orderId;
				new Thread(new Runnable() {

					@Override
					public void run() {
						//恢复商品对应规格的库存
						List<OrderDetail> orderDetailList = orderService.selectOrderDetailList(orderId_);
						if(orderDetailList != null && orderDetailList.size() > 0){
							for(OrderDetail detail :orderDetailList){
								GoodsStock stock = new GoodsStock();
								stock.setGoodsId(detail.getProductId());
								String goods_sku_values = detail.getGoods_sku_info();
								if(Common.isNotEmpty(goods_sku_values)){
									stock = goodsService.getGoodsStock(stock, goods_sku_values.split(","));
								}
								stock.setSaleBaseQuantity(Integer.valueOf((detail.getNumber())));
								int updateGoodsStockResult = goodsService.updateGoodsStock(stock);
								if(updateGoodsStockResult  <= 0){
								}
							}
						}
					}
				}).start();
				*/
			}else if(Constants.OrderDetail.STATUSB.equals(status)){
				order.setStatus(Constants.OrderDetail.OrderStatus.ORDER_STATUSB);
				order.setIsDelete(Constants.OrderDetail.OrderStatus.IS_DELETEB);
			}
			int cancelOrDeleteOrderResult =  orderService.updateOrder(order);
			if(cancelOrDeleteOrderResult > 0){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			}else{
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_UPDATE);
			}
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FAIL);
		}
		return resultMap;
	}
	/**
	 * @Title: ordersPay
	 * @Description 订单付款(单个订单付款;暂不支持合并付款)
	 * @param param //订单ID payType   支付类型 1:支付宝 2:微信 3:银联 4:畅捷通快捷支付，5.畅捷通微信支付，6：其它支付方式
	 * @date 2017年3月13日上午11:55:35
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value="/ordersPay",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> ordersPay(HttpServletRequest request, String param){		
		Map<String,Object> resultMap=new HashMap<String,Object>();
		AppPay qPay = new AppPay();
		String strResult="";
		AppPayResult result = null;
		Order order = new Order();
		Map<String, String> origMap = new LinkedHashMap<String, String>();
		try{	
			if(Common.isEmpty(param)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			OrdersPay pay = JSON.parseObject(param,OrdersPay.class);
			String orderId = pay.getOrderId();
			if(Common.isEmpty(orderId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_ID_IS_NULL);
				return resultMap;
			}
			order = orderService.selectByPrimaryKey(orderId);
			if(order == null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_FIND_ERROR);
				return resultMap;
			}	
			String totalAmount = pay.getTotalAmount();
			if(Common.isEmpty(totalAmount)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_AMOUNT_IS_NULL);
				return resultMap;
			}
			String payType = pay.getPayType();
			if(Common.isEmpty(payType)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_PAY_TYPE_IS_NULL);
				return resultMap;
			}
		    String buyerIp =Common.getIpAddr(request);	
		    
			Integer cardId = pay.getCardId();
			if(cardId == null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_PAY_CARD_ID_IS_NULL);
				return resultMap;
			}

			order.setOrderId(orderId);
		    OrderPayment payment = new OrderPayment();
		    payment.setOrderId(order.getOrderId());
			if("7".equals(payType)){//微信app支付

				String noncestr="";
				String timestamp="";
				//开始向微信下单
				strResult=qPay.wxAppPay(orderId, totalAmount, "",ConfigBeanAdapter.notify_url);
				if(Common.isEmpty(strResult)){
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_WEIXIN_ORDER_CREATE_ERROR);
				}
				result = JSON.parseObject(strResult, AppPayResult.class);		
			    //从微信读取成功的下单信息 
				if (result.getAuthenticate_status().equals("0")) {
					updateOrderStatus("success",payType, order, null, noncestr, timestamp, resultMap);
				}else{
					updateOrderStatus("fail", payType,order, null, noncestr, timestamp, resultMap);
				}
		        payment.setPayName("微信app支付");
			}else if("1".equals(payType)){ //畅捷通快捷银联支付
				order.setPayDeadline(DateUtil.getDateAfter(order.getCreateDate(),  Integer.valueOf(ConfigBeanAdapter.chan_qpay_order_expired_time)));//支付截止时间默认7天
				String realName="";
				String cardNumber="";
				String idNumber = "";
			    String phone ="";
			    String bankName="";
				MemberCard card = new MemberCard();
				card = memberCardService.selectByPrimaryKey(cardId);
				if(card != null){
					realName = card.getRealName();
					cardNumber = card.getCardNumber();
					idNumber = card.getIdNumber();
					phone = card.getPhone();
					bankName = card.getBankName();
				}			
			    String instCode = BankCodeNameEnum.getInstNameByCode(bankName);		
				System.out.println("out_trade_no"+orderId);//商户订单号
				System.out.println("total_amount"+totalAmount );
		        origMap.put("out_trade_no",orderId);// 订单号
		        origMap.put("trade_amount", totalAmount);// 金额
		        origMap.put("buyer_ip",buyerIp);//用户在商户平台下单时候的公网IP地址
		        origMap.put("bank_code",instCode);//银行编码
		        origMap.put("payer_name", realName);//付款方名称
		        origMap.put("payer_card_no", cardNumber);//付款方银行卡号
		        origMap.put("id_number",idNumber);//身份证号
		        origMap.put("phone_number",phone);//手机号
                origMap.put("user_sign",order.getCreater());//商户网站用户唯一标识，用用户ID标识
                List<Products> products = orderService.selectOrderProductsByOrderId(orderId);
                origMap.put("product_name",products.get(0).getProductName());//商品名称
                origMap.put("order_time",DateUtil.dateToString(order.getCreateDate()));//商户订单提交时间
                origMap.put("expired_time", ConfigBeanAdapter.chan_qpay_order_expired_time+"d"); //支付过期时间 //默认7天取值范围：1m～15d。m-分钟，h-小时，d-天。 该参数数值不接受小数点，如1.5h，可转换为90m。
       
				//畅捷通快捷支付
				strResult = qPay.createQPay(origMap,ConfigBeanAdapter.notify_url);
				if(Common.isEmpty(strResult)){
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_ORDER_CREATE_ERROR);
					return resultMap;
				}
				result = JSON.parseObject(strResult, AppPayResult.class);	
				if(result.getIs_success().equals("F")){
					//DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_ORDER_CREATE_ERROR);
					resultMap.put("resultSuccess",false);
					resultMap.put("resultDesc", result.getErr_msg()==null?result.getError_message():result.getErr_msg());
					return resultMap;					
				}
			    //畅捷通快捷支付读取成功的下单信息 
				resultMap.put("outer_trade_no", orderId);
				resultMap.put("trade_amount",totalAmount);	
				order.setPayStatus(Constants.OrderDetail.OrderPay.PAY_STATUSC);
			    payment.setPayType(Constants.OrderDetail.OrderPay.PayType.PAY_TYPEB); //支付类型 1:畅捷通快捷银联支付 2.畅捷通微信扫码支付 3：畅捷通支付宝扫码支付 4.畅捷通微信app支付 5：畅捷通支付宝app支付 6：微信公众号支付 7：微信app支付 8：其它支付	          
		       	
				resultMap =updateOrderStatus( order,result,resultMap);
				if(Common.isNotEmpty(cardNumber))
			       payment.setPaymentAccount(cardNumber);
				if(Common.isNotEmpty(bankName))
			       payment.setPaymentBank(bankName);
				if(Common.isNotEmpty(phone))
			       payment.setPhone(phone);
				if(Common.isNotEmpty(idNumber))
					payment.setIdNumber(idNumber);
				if(Common.isNotEmpty(buyerIp))
					payment.setByerIp(buyerIp);
				if(Common.isNotEmpty(realName))
					payment.setPayer(realName);
			    payment.setPayName("畅捷通快捷银联支付");  
			    payment.setPayType(Constants.OrderDetail.OrderPay.PayType.PAY_TYPEA); //支付类型 1:畅捷通快捷银联支付 2.畅捷通微信扫码支付 3：畅捷通支付宝扫码支付 4.畅捷通微信app支付 5：畅捷通支付宝app支付 6：微信公众号支付 7：微信app支付 8：其它支付	          
		          
			}
		    orderService.updateOrderPayment(payment);
			
			
		}catch(Exception e){
			e.printStackTrace();
	    	DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_ORDER_CREATE_ERROR);
		}		
		return resultMap;
	}
    /**
     *  畅捷通快捷支付
     * @param order
     * @param result
     * @param resultMap
     * @return
     */
	public Map<String,Object> updateOrderStatus(Order order,AppPayResult result,Map<String,Object> resultMap){	
		if("F".equals(result.getIs_success())){
			order.setPayStatus(Constants.OrderDetail.OrderPay.PAY_STATUSD);
	    	DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_ORDER_CREATE_ERROR);
			return resultMap;
		}else{
		    resultMap.put("authenticate_status", result.getAuthenticate_status());
		   // resultMap.put("sign", result.getSign());
		   // resultMap.put("sign_type", result.getSign_type());
			//畅捷通快捷支付付款截止时间
		    if("0".equals(result.getAuthenticate_status())){
			    order.setPayDeadline(DateUtil.getDateAfter(new Date(), Integer.valueOf(ConfigBeanAdapter.chan_qpay_order_expired_time)));
				if(Common.isEmpty(result.getErr_msg())){
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_ORDER_CREATE_SUCCESS);
				}else{
					resultMap.put("resultDesc", result.getErr_msg());
				}
			}else{	
				resultMap.put("resultSuccess",false);
			    resultMap.put("resultDesc", result.getErr_msg());
			}
		}		
	    int updateOrderResult = orderService.updateOrder(order);
	    if(updateOrderResult == 0){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_UPDATE_ERROR);
	    } 
		return resultMap;
	}
	/**
	 * @Title qPayConfirm
	 * @Description 快捷支付交易确认接口
	 * @param out_trade_no
	 * @param verification_code
	 * @date 2017年3月21日下午14:50:35
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value="/qPayConfirm",method=RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> qPayConfirm(String out_trade_no,String verification_code){
		Map<String,Object> resultMap=new HashMap<String,Object>();
		AppPay qPay = new AppPay();
		AppPayResult result = new AppPayResult();
		try{
            if(Common.isEmpty(out_trade_no) ){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_ID_IS_NULL);
    			return resultMap;
            }
            if(Common.isEmpty(verification_code)){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_VERIFICATION_CODE_IS_NULL);
    			return resultMap;
            }
			resultMap.put("out_trade_no", out_trade_no);
            String returnParam =  qPay.createQPayConfirm(out_trade_no, verification_code);
			result = JSON.parseObject(returnParam, AppPayResult.class);
			if(result == null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_CONFIRM_REQUEST_ERROR);
				return resultMap;
			}
			if(Common.isNotEmpty(result.getErr_msg())){
				resultMap.put("resultSuccess",false);
				resultMap.put("resultDesc", result.getErr_msg());
				return resultMap;
			}
			if(result.getIs_success().equals("F")){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_CONFIRM_REQUEST_ERROR);
				return resultMap;
			}
			if("0".equals(result.getTrade_status())){//0：支付成功
				System.out.println("支付成功");
			}else if("1".equals(result.getTrade_status())){//1：支付处理中

				System.out.println("支付处理中");
			}else if("2".equals(result.getTrade_status())){//2：支付失败
				resultMap.put("resultSuccess",false);
				resultMap.put("resultDesc", result.getErr_msg());
				System.out.println("支付失败");
				
			}
			/*resultMap.put("error_code", result.getError_code());
			resultMap.put("error_message", result.getError_message());
			resultMap.put("is_success", result.getIs_success());
			resultMap.put("memo", result.getIs_success());
			resultMap.put("memo", result.getMemo());
			resultMap.put("sign", result.getSign());*/
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_CONFIRM_REQUEST_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_CONFIRM_REQUEST_ERROR);
			return resultMap;
		}
		
		return resultMap;
	}

	/**
	 * 根据微信app支付下单反馈情况,通知app请求下单结果
	 * @param flag
	 * @param pay_type // 1:畅捷通快捷银联支付 2.畅捷通微信扫码支付 3：畅捷通支付宝扫码支付 4.畅捷通微信app支付 5：畅捷通支付宝app支付 6：微信公众号支付 7：微信app支付 8：其它支付
	 * @param order
	 * @param xml
	 * @param noncestr
	 * @param timestamp
	 * @param resultMap
	 * @return
	 */
	public Map<String,Object> updateOrderStatus(String flag,String pay_type,Order order,Map<String,Object> xml,String noncestr,String timestamp,Map<String,Object> resultMap){
	
		SortedMap<Object,Object> parameters=new TreeMap<Object,Object>();
		parameters.put("appid", xml.get("appid"));
	    parameters.put("partnerid", xml.get("mch_id"));
	    parameters.put("prepayid", xml.get("prepay_id"));
	    parameters.put("package", "Sign=WXPay");
	    parameters.put("noncestr", noncestr);
	    parameters.put("timestamp", timestamp);
	    String sign=WeiXin.createSign("utf-8", parameters);
	    parameters.put("sign", sign);
	    
	    logger.info("sign:"+sign);
	    logger.info("noncestr:"+noncestr);
	    logger.info("timestamp"+timestamp);
	    logger.info("prepayid"+xml.get("prepay_id"));

	    resultMap.put("noncestr", noncestr);
	    resultMap.put("timestamp", timestamp);
	    resultMap.put("prepayid", xml.get("prepay_id"));
	    resultMap.put("sign", sign);
	    if("success".equals(flag)){
		    //微信支付2小时之内付款
	        if("2".equals(pay_type)){
		    	order.setPayDeadline(DateUtil.getDateAfter(new Date(), 2));
		    }
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_WEIXIN_ORDER_CREATE_SUCCESS);
	    }else if("fail".equals(flag)){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_WEIXIN_ORDER_CREATE_ERROR);
			return resultMap;
	    }
	    int updateOrderResult = orderService.updateOrder(order);
	    if(updateOrderResult == 0){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_UPDATE_ERROR);
	    }
		return resultMap;
	}
	/**
	 * @Title: notify
	 * @Description 畅捷通快捷通支付结果通知
	 * @param request 
	 * @param response
	 * @date 2017年3月13日上午11:55:35
	 * @author LeiJia  
	 * @return 
	 */
	@RequestMapping(value="/notifyQpay")
	@ResponseBody
	public void notifyQpay(HttpServletRequest request,HttpServletResponse response) throws Exception{
		try{
			if(request.getParameter("outer_trade_no") == null || request.getParameter("inner_trade_no") == null 
					|| request.getParameter("trade_status") == null || request.getParameter("trade_amount") == null || request.getParameter("gmt_create") == null ){
				return;
			}

			//商户订单号	
	    	String out_trade_no=(String) request.getParameter("outer_trade_no");
	    	//交易订单号
	    	String inner_trade_no = (String) request.getParameter("inner_trade_no");
	    	//交易状态
	    	String trade_status =(String) request.getParameter("trade_status");
	    	//交易金额
	    	BigDecimal total_fee=new BigDecimal(request.getParameter("trade_amount"));
	    	//交易通知时间
	    	//String notify_time=(String)request.getParameter("notify_time");
	    	//交易创建时间
	    	String gmt_create = (String) request.getParameter("gmt_create");
	    	//交易支付时间
	    	String gmt_payment = (String) request.getParameter("gmt_payment");    	
	        //交易关闭时间
	    	String gmt_close="";
	    	if(request.getParameter("gmt_close") != null){
	    		gmt_close = (String) request.getParameter("gmt_close"); 
	    	}
        	Order order = new Order();
	    	order.setOrderId(out_trade_no);
	    	order = orderService.selectByPrimaryKey(out_trade_no);	    			
	    	OrderPayment payment= new OrderPayment();
	    	payment.setOrderId(out_trade_no);//商品订单号        	
	    	List<OrderPayment> list = orderService.selectByPayments(payment);
	    	
	    	//2017年4月5日修改,由于当前系统只支持单店铺，不存在提交一个订单，生成多个支付详单的情况，默认一个订单生成一个支付详单
	    	payment = list.get(0);
	    	if(order !=null && payment != null){ 
		    	String order_payment_status_now = payment.getStatus();
		    	String order_pay_status_now = order.getPayStatus();

				//如果订单支付当前状态已经是提交到银行,不再重复修改订单支付状态，通知畅捷通成功
				if(Constants.OrderDetail.OrderPay.PAY_STATUSF.equals(order_payment_status_now) && Constants.OrderDetail.OrderPay.PAY_STATUSF.equals(order_pay_status_now)){
	            	response.getWriter().write("success");
				}
	            //如果订单当前支付状态已经是支付完成,不再重复修改订单支付状态，通知畅捷通成功
				if( Constants.OrderDetail.OrderPay.PAY_STATUSA.equals(order_payment_status_now) && Constants.OrderDetail.OrderPay.PAY_STATUSA.equals(order_pay_status_now)){
	            	response.getWriter().write("success");
				}
	            payment.setPayType(Constants.OrderDetail.OrderPay.PayType.PAY_TYPEA);//支付类型 1:畅捷通快捷银联支付 2.畅捷通微信扫码支付 3：畅捷通支付宝扫码支付 4.畅捷通微信app支付 5：畅捷通支付宝app支付 6：微信公众号支付 7：微信app支付 8：其它支付
	            payment.setPayName("畅捷通快捷银联支付");//支付名称
	            payment.setMoney(total_fee);//支付金额
	            payment.setType(Constants.OrderDetail.OrderPay.PayType.TYPEB);//交易类型
	            payment.setPayCreate(DateUtil.dateStrToDate(gmt_create));
	            payment.setPayTime(DateUtil.dateStrToDate(gmt_payment));
	            payment.setPayClose(DateUtil.dateStrToDate(gmt_close));
	            payment.setTransactionId(inner_trade_no);
	    		if("TRADE_SUCCESS".equals(trade_status)){
	    			payment.setModifyDate(new Date());
	                payment.setStatus(Constants.OrderDetail.OrderPay.PAY_STATUSF);//付款状态
					order.setPayStatus(Constants.OrderDetail.OrderPay.PAY_STATUSF);
	                int insertPaymentResult =  orderService.updateOrderPayment(payment);
	                int insertOrderResult = orderService.updateOrder(order);
		            if(insertPaymentResult > 0 && insertOrderResult > 0){
		            	if("false".equals(ConfigBeanAdapter.isEnable_quartz_start)){ //读取配置文件配置标识
			            	final Order order_ = order;
			            	//将订单上传到T+系统中
			            	new Thread(new Runnable() {
								
								@Override
								public void run() {
									orderService.addOrderToTSaleOrder(order_);
								}
							}).start();
						 }
		            	response.getWriter().write("success");
				    	
		            }
	    		}else if("TRADE_FINISHED".equals(trade_status)){
	    			payment.setModifyDate(new Date());
	                payment.setStatus(Constants.OrderDetail.OrderPay.PAY_STATUSA);//付款状态
					order.setPayStatus(Constants.OrderDetail.OrderPay.PAY_STATUSA);
	                int insertPaymentResult =  orderService.updateOrderPayment(payment);
	                int insertOrderResult = orderService.updateOrder(order);
		            if(insertPaymentResult > 0 && insertOrderResult > 0){
		            	if("false".equals(ConfigBeanAdapter.isEnable_quartz_start)){ //读取配置文件配置标识
			            	final Order order_ = order;
			            	//将订单上传到T+系统中
			            	new Thread(new Runnable() {
								
								@Override
								public void run() {
									orderService.addOrderToTSaleOrder(order_);
								}
							}).start();
						 }
		            	response.getWriter().write("success");
		            }
	    		}
	    	}
	    
		}catch(Exception e){
			e.printStackTrace();
	    	response.getWriter().write("false");
		}
    	response.getWriter().write("false");
	}
	/**
	 * @Title payDetail
	 * @Description  通过订单ID获取订单支付结果
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="payDetail",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> payDetail(String orderId){
		Map<String,Object> resultMap=new LinkedHashMap<String,Object>();
		try{
			if(Common.isEmpty(orderId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_ID_IS_NULL);
				return resultMap;
			}

			if(Common.isEmpty(orderId) ){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_FIND_ERROR);
				return resultMap;
			}
			List<OrderPayment> list =new ArrayList<OrderPayment>();
			OrderPayment payment =new OrderPayment();
			payment.setOrderId(orderId);
			
			list =orderService.selectByPayments(payment);
	    	
	    	//2017年4月5日修改,由于当前系统只支持单店铺，不存在提交一个订单，生成多个支付详单的情况，默认一个订单生成一个支付详单
			payment = list.get(0);
			if(payment.getStatus().equals(Constants.OrderDetail.OrderPay.PAY_STATUSC)){	
				resultMap.put("status", Constants.OrderDetail.OrderPay.PAY_STATUSC);			
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_NOTPAY);
			}else{
				if(payment.getStatus().equals(Constants.OrderDetail.OrderPay.PAY_STATUSF)){
					resultMap.put("status", Constants.OrderDetail.OrderPay.PAY_STATUSF);
				//	DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_MONEY_TO_BANK);
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_SUCCESS);
				}else if(payment.getStatus().equals(Constants.OrderDetail.OrderPay.PAY_STATUSA)){
					resultMap.put("status", Constants.OrderDetail.OrderPay.PAY_STATUSA);
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CHAN_QPAY_SUCCESS);
				}
			}			
			resultMap.put("orderId", payment.getOrderId());
			resultMap.put("transactionId", payment.getTransactionId());
			resultMap.put("paymentBank", payment.getPaymentBank());
			resultMap.put("paymentAccount", payment.getPaymentAccount());
			resultMap.put("money", payment.getMoney());
			resultMap.put("payer", payment.getPayer());
			resultMap.put("payType", payment.getPayType());
			resultMap.put("curMoney", payment.getCurMoney());
			resultMap.put("payCreate", payment.getPayCreate());
			resultMap.put("payClose", payment.getPayClose());
			resultMap.put("payTime", payment.getPayTime());
			resultMap.put("type", payment.getType());
			resultMap.put("payName", payment.getPayName());
			
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
	/**
	 * @Title: notify
	 * @Description  微信支付结果通知
	 * @param request 
	 * @param response
	 * @date 2017年3月13日上午11:55:35
	 * @author LeiJia  
	 * @return 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/notify")
	@ResponseBody
	public void notify(HttpServletRequest request,HttpServletResponse response) throws Exception{
		InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        logger.info("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
        outSteam.close();
        inStream.close();
        //获取微信调用我们notify_url的返回信息
        String result  = new String(outSteam.toByteArray(),"utf-8");        
        Map<Object, Object> map = XMLUtil.doXMLParse(result);
        for(Object keyValue : map.keySet()){
        	logger.info(keyValue+"="+map.get(keyValue));
        }
        logger.info("微信支付状态码=================》》"+map.get("result_code").toString());
    	if (CollectionUtil.isNotEmpty(map) && "SUCCESS".equals(map.get("result_code"))) {
        	logger.info("执行success执行下面这一步");
        	updateOrderPayStatus(response,"success",map);
        	logger.info("回调结束");
        	
        	//此处要将订单信息上传到T+系统
    		response.getWriter().write(setXML("SUCCESS", "success"));
        }else{
        	logger.info("执行fail执行下面这一步");
        	updateOrderPayStatus(response,"fail",map);
        	response.getWriter().write(setXML("FAIL", "fail"));
        }
	}
	
	/**
	 * 微信支付结果通知后修改订单付款状态
	 * @param flag
	 * @param map
	 */
	public void updateOrderPayStatus(HttpServletResponse response,String flag , Map<Object, Object> map){
		try{
			//商户订单号	
	    	String out_trade_no=map.get("out_trade_no").toString();
	    	String total_fee=map.get("total_fee").toString();
	    	//String money=Double.parseDouble(total_fee)/100+"";
	    	BigDecimal  money = BigDecimal.valueOf(Double.parseDouble(total_fee)).multiply(BigDecimal.valueOf(100))
					.setScale(0, BigDecimal.ROUND_HALF_UP);
	    	System.out.println("订单号："+out_trade_no);
	    	System.out.println("订单金额："+money);
	    	OrderPayment payment= new OrderPayment();
	    	payment.setOrderId(out_trade_no);//商品订单号  
	    	List<OrderPayment> list = orderService.selectByPayments(payment);
	    	
	    	//2017年4月5日修改,由于当前系统只支持单店铺，不存在提交一个订单，生成多个支付详单的情况，默认一个订单生成一个支付详单
	    	payment = list.get(0);
    		if(payment != null){            	
    			payment.setPayType(Constants.OrderDetail.OrderPay.PayType.PAY_TYPEG);//支付类型 1:畅捷通快捷银联支付 2.畅捷通微信扫码支付 3：畅捷通支付宝扫码支付 4.畅捷通微信app支付 5：畅捷通支付宝app支付 6：微信公众号支付 7：微信app支付 8：其它支付
	            payment.setPayName(WinXinReturnEnum.TRADE_TYPE_APP.getDesc());//支付名称
    			payment.setMoney(money);//支付金额
    			payment.setType(Constants.OrderDetail.OrderPay.PayType.TYPEA);//交易类型

	    		if("success".equals(flag)){

	    			payment.setStatus(Constants.OrderDetail.OrderPay.PAY_STATUSA);//付款状态
	    		}else if("fail".equals(flag)){
	    			payment.setStatus(Constants.OrderDetail.OrderPay.PAY_STATUSB);//付款状态
	    		}
	            String time_end = map.get("time_end").toString();
	            payment.setPayTime(DateUtil.dateStrToDate(time_end));
	            payment.setTransactionId(map.get("transaction_id").toString());
	            int insertPaymentResult =  orderService.insert(payment);
	            if(insertPaymentResult == 0){
	            	response.getWriter().write(setXML("FAIL", "fail"));
	            }
	    	}
	    	
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	
	public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code
                + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
	}
	
	/**
	 * @Title: confirmReceiptOrder
	 * @Description 确认收货
	 * @date 2017年3月16日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value = "confirmReceiptOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> confirmReceiptOrder(HttpServletRequest request,String orderId,String memberId){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			if(Common.isEmpty(orderId) || Common.isEmpty(memberId)){				
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
			}
			Order order = new Order();
			order.setOrderId(orderId);
			order.setShipStatus(Constants.OrderDetail.OrderDeliver.SHIP_STATUSF);
			order.setStatus(Constants.OrderDetail.OrderStatus.ORDER_STATUSD);
			order.setIsDelete(Constants.IS_DELETEA);
			int confirmReceiptOrderResult =  orderService.updateOrder(order);
			if(confirmReceiptOrderResult > 0){

				MemberNews news = new MemberNews(); //交易物流消息
				news.setCreater(memberId);
		    	news.setModifier(memberId);
				news.setOrderId(orderId);
		    	news.setMemberId(memberId);
				news.setNewsTitle(Constants.OrderDetail.OrderDeliver.SHIP_STATUS_TITLEF);
		    	news.setCreateDate(new Date());
		    	news.setModifyDate(new Date()); 
		    	//生成一条消息通知
				orderService.insertMemberNews(news);
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			}else{
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_UPDATE);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultMap;
	}

}
